package com.example.wx.utils;

import net.sf.json.JSONObject;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.HashMap;
import java.util.Map;

/**
 * desc: 获取用户openid
 * date: 2020/04/26
 * auth: leo
 */
public class GetOpenIdUtils {
    public static Map<String, Object> oauth2GetOpenid(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + ParamUtils.APPID + "&secret=" + ParamUtils.SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        DefaultHttpClient client = null;
        Map<String, Object> result = new HashMap<>();
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            String openid = String.valueOf(OpenidJSONO.get("openid"));
            String session_key = String.valueOf(OpenidJSONO.get("session_key"));
            String unionid = String.valueOf(OpenidJSONO.get("unionid"));
            String errcode = String.valueOf(OpenidJSONO.get("errcode"));
            String errmsg = String.valueOf(OpenidJSONO.get("errmsg"));

            result.put("openid", openid);
            result.put("sessionKey", session_key);
            result.put("unionid", unionid);
            result.put("errcode", errcode);
            result.put("errmsg", errmsg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert client != null;
            client.getConnectionManager().shutdown();
        }
        return result;
    }
}
